package com.wgj.android.web;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.jiaai.xui.base.XActivity;
import com.jiaai.xui.view.widget.XTopbarView;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;
import com.wgj.android.R;
import com.wgj.android.utils.utils.X5WebView;
import com.wgj.android.web.entity.WebConfig;

/**
 * Created by Administrator on 2017/10/27.
 */

public class WGJWebActivity extends XActivity {
    public  static  final  String WEB_CONFIG="web_config";
    public  static  final String  TAG ="HTML5";
    private XTopbarView topbarView;
    private X5WebView mWebView;
    private ViewGroup mViewParent;
    private ProgressBar mPageLoadingProgressBar = null;
    private  WebConfig config;

    public static void openHtml5(Context context,String url){
        openHtml5(context,new WebConfig(url));
    }
    public static void openHtml5(Context context,String url,boolean isShowTopBar){
        WebConfig config=new WebConfig(url);
        config.setShowTopBar(isShowTopBar?1:0);
        openHtml5(context,config);
    }
    public static void openHtml5(Context context,WebConfig webConfig){
        Intent intent = new Intent(context, WGJWebActivity.class);
        intent.putExtra(WEB_CONFIG,webConfig);
        context.startActivity(intent);
    }
    @Override
    public int getLayoutId() {
        return R.layout.wgj_web_activity;
    }

    @Override
    public void initData(Bundle bundle) {
         //EventBus.getDefault().register(this);
         config= (WebConfig) getIntent().getExtras().getSerializable(WEB_CONFIG);

    }

    @Override
    public void initView() {

        topbarView=findViewById(R.id.topBar);
        if(config.getShowTopBar()!=1){
            topbarView.setVisibility(View.GONE);
        }
        mViewParent = (ViewGroup) findViewById(R.id.webView1);

        mWebView = new X5WebView(this, null);

        mViewParent.addView(mWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT));

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(com.tencent.smtt.sdk.WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(com.tencent.smtt.sdk.WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });

        mWebView.setWebChromeClient(new com.tencent.smtt.sdk.WebChromeClient() {

            @Override
            public boolean onJsConfirm(com.tencent.smtt.sdk.WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
               // return super.onJsConfirm(arg0, arg1, arg2, arg3);
                return  false;
            }

            View myVideoView;
            View myNormalView;
            IX5WebChromeClient.CustomViewCallback callback;

            // /////////////////////////////////////////////////////////
            //
            /**
             * 全屏播放配置
             */
            @Override
            public void onShowCustomView(View view,
                                         IX5WebChromeClient.CustomViewCallback customViewCallback) {
                FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
                ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                viewGroup.removeView(normalView);
                viewGroup.addView(view);
                myVideoView = view;
                myNormalView = normalView;
                callback = customViewCallback;
            }

            @Override
            public void onHideCustomView() {
                if (callback != null) {
                    callback.onCustomViewHidden();
                    callback = null;
                }
                if (myVideoView != null) {
                    ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                    viewGroup.removeView(myVideoView);
                    viewGroup.addView(myNormalView);
                }
            }

            @Override
            public boolean onJsAlert(com.tencent.smtt.sdk.WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
               // return super.onJsAlert(null, arg1, arg2, arg3);
                return  false;
            }
        });

        mWebView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String arg0, String arg1, String arg2,
                                        String arg3, long arg4) {
                TbsLog.d(TAG, "url: " + arg0);
//                new AlertDialog.Builder(WGJWebActivity.this)
//                                                .setTitle("allow to download？")
//                                                .setPositiveButton("yes",
//                                                        new DialogInterface.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(DialogInterface dialog,
//                                                                                int which) {
//                                                                Toast.makeText(
//                                                                        WGJWebActivity.this,
//                                                                        "fake message: i'll download...",
//                                                                        Toast.LENGTH_SHORT).show();
//                                                            }
//                                                        })
//                                                .setNegativeButton("no",
//                                                        new DialogInterface.OnClickListener() {
//
//                                                            @Override
//                                                            public void onClick(DialogInterface dialog,
//                                                                                int which) {
//                                                                // TODO Auto-generated method stub
//                                                                Toast.makeText(
//                                                                        WGJWebActivity.this,
//                                                                        "fake message: refuse download...",
//                                                                        Toast.LENGTH_SHORT).show();
//                                                            }
//                                                        })
//                                                .setOnCancelListener(
//                                                        new DialogInterface.OnCancelListener() {
//
//                                                            @Override
//                                                            public void onCancel(DialogInterface dialog) {
//                                                                // TODO Auto-generated method stub
//                                                                Toast.makeText(
//                                                                        WGJWebActivity.this,
//                                                                        "fake message: refuse download...",
//                                                                        Toast.LENGTH_SHORT).show();
//                                    }
//                                }).show();
            }
        });

        com.tencent.smtt.sdk.WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(com.tencent.smtt.sdk.WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
//		if (mIntentUrl == null) {
//			mWebView.loadUrl(mHomeUrl);
//		} else {
//			mWebView.loadUrl(mIntentUrl.toString());
//		}
        mWebView.loadUrl(	config.getUrl());

        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        if(config.getShowTopBar()==1){
            topbarView.setVisibility(View.VISIBLE);
            topbarView.setTitle(config.getTitle());
        }else{
            topbarView.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000) {
            mWebView.loadUrl(config.getUrl());
            return;
        }
        mWebView.onActivityResult(requestCode, resultCode, data);
        // mAgentWeb.getJsAccessEntrace().quickCallJs("window.onSelecttMapCallback();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 16)

                return true;
            } else
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        config= (WebConfig) getIntent().getExtras().getSerializable(WEB_CONFIG);
        mWebView.loadUrl(config.getUrl());
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null)
            mWebView.destroy();
        super.onDestroy();
    }

    /*@Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinish(String finish){
        finish();
    }*/
}
